""" session.py

This module provides the session data class.

   Copyright 2011 Bravo369.org

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

author = Mike Meade (mmeade@google.com)
"""

# General imports
import random
import string
import time

# Application imports
from data import datastore

# Framework imports
from google.appengine.ext import db


class Session(datastore.ModelBase):
  """A datastore-based session class."""

  id_key = db.StringProperty()
  start_time = db.FloatProperty()
  save = bool()
  _json_keys = ['id_key', 'save']

  @classmethod
  def _createRandomKey(cls, length=6):
    """Create a simple random key.

    Args:
      length: The length of the key.

    Returns:
      A random string of the indicated length.
    """
    return ''.join(
        random.sample(string.ascii_uppercase + string.digits, length)
        )

  @classmethod
  def _getUniqueKey(cls, length=6):
    """Get a unique session key.

    Args:
      length: The length of the key.

    Returns:
      A unique session key of the indicated length.
    """
    while True:
      key = cls._createRandomKey()
      all = cls.all()
      all.filter('id_key =', key)
      if not all.fetch(1):
        return key

  @classmethod
  def createNewSessionKey(cls):
    """Create, save, and return a new session key.

    Returns:
      A new unique random session key.
    """
    instance = cls(
        id_key=cls._getUniqueKey(),
        start_time=time.time()
        )
    instance.put()
    return instance
